
package com.hnas.common.web;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;

import java.util.Random;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



public class RandomCodeServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private int width = 60;

	private int height = 20;

	/**
	 * @param fc
	 * c
	 * @param bc
	 * c
	 * @return c
	 */
	Color getRandColor(int fc, int bc) {

		Random random = new Random();

		if (fc > 255) {
			fc = 255;
		}

		if (bc > 255) {
			bc = 255;
		}

		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);

		return new Color(r, g, b);
	}

	/**
	 *
	 *
	 * @param req c
	 * @param resp c
	 *@throws java.io.IOException c
	 * @throws ServletException c
	 */
	protected void service(HttpServletRequest req, HttpServletResponse resp)
	{//  throws ServletException, java.io.IOException
		try{
			BufferedImage buffImg = new BufferedImage(width, height,
					BufferedImage.TYPE_INT_RGB);
			Graphics2D g = buffImg.createGraphics();


			Random random = new Random();

			g.setColor(getRandColor(200, 250));
			g.fillRect(0, 0, width, height);


			Font font = new Font("", Font.BOLD, 18); // 


			g.setFont(font);

			// 
			g.setColor(Color.BLACK);
			g.drawRect(0, 0, width - 1, height - 1);

			// 
			g.setColor(getRandColor(160, 200));

			for (int i = 0; i < 155; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int xl = random.nextInt(12);
				int yl = random.nextInt(12);
				g.drawLine(x, y, x + xl, y + yl);
			}

			// 
			StringBuffer randomCode = new StringBuffer();
			int red = 0;
			int green = 0;
			int blue = 0;

			// 
			for (int i = 0; i < 4; i++) {
				//
				String strRand = String.valueOf(random.nextInt(10));

				//
				red = random.nextInt(110);
				green = random.nextInt(50);
				blue = random.nextInt(50);

				//
				g.setColor(new Color(red, green, blue));

				g.drawString(strRand, (13 * i) + 6, 16);

				//
				randomCode.append(strRand);
			}

			//
			HttpSession session = req.getSession();
			session.setAttribute("authCode", randomCode.toString());
			g.dispose();
			//
			resp.setHeader("Pragma", "no-cache");
			resp.setHeader("Cache-Control", "no-cache");
			resp.setDateHeader("Expires", 0);
			resp.setCharacterEncoding("UTF-8");
			resp.setContentType("image/jpeg");

			//
			ServletOutputStream sos = resp.getOutputStream();
			ImageIO.write(buffImg, "jpeg", sos);
			sos.close();
		}catch (Throwable t) {
			
		}
	}
}
